package com.california.pay.socket.server;

import com.bwton.socket.codec.ServerCodec;
import com.bwton.socket.extension.SpiMeta;
import com.bwton.socket.transport.Channel;
import com.bwton.socket.transport.URL;
import com.bwton.socket.transport.call.Request;
import com.bwton.socket.transport.call.Response;
import com.bwton.socket.transport.call.SocketMessage;
import com.california.pay.socket.TransSocketMessage;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;

/**
 * 客户端编码器示例
 */
@SpiMeta(name = "socketServerCodec")
public class SocketServerCodec implements ServerCodec {
    private static final Logger logger = LoggerFactory.getLogger(SocketServerCodec.class);

    private URL url;

    @Override
    public byte[] encode(Channel channel, Response response) {
        // 要做异常捕捉
        SocketMessage socketMessage = response.getValue();

        TransSocketMessage transSocketMessage = (TransSocketMessage)socketMessage;
        String socketBody = transSocketMessage.getSocketBody();

        if (StringUtils.isNotBlank(socketBody)){
            try {
                return socketBody.getBytes("utf-8");
            } catch (UnsupportedEncodingException e) {
                logger.error("SocketServerCodec中字符串转二进制异常，socketBody=" + socketBody, e);
                e.printStackTrace();
            }
        }

        return null;
    }

    @Override
    public Request decode(Channel channel, String s, SocketMessage socketMessage, Request request) {
        return request;
    }

    @Override
    public void setUrl(URL url) {
        this.url = url;
    }
}
